/**
 * 
 */
package org.jms.examples.openjmsexamples.p2p;

import java.util.Date;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * @author Sudarsan
 *
 */
public class Sender {

	private Context context = null;
	private QueueConnectionFactory connectionFactory = null;
	private QueueConnection connection = null;
	private Queue queue = null;
	private QueueSender sender = null;
	private QueueSession session = null;

	public void sendMessage() {
		Properties properties = new Properties();
		properties.put(InitialContext.INITIAL_CONTEXT_FACTORY,
				"org.exolab.jms.jndi.InitialContextFactory");
		properties.put(InitialContext.PROVIDER_URL, "tcp://localhost:3035");

		try {
			context = new InitialContext(properties);
			connectionFactory = (QueueConnectionFactory) context
					.lookup("ConnectionFactory");
			queue = (Queue) context.lookup("queue1");
			connection = connectionFactory.createQueueConnection();
			session = connection.createQueueSession(false,
					QueueSession.AUTO_ACKNOWLEDGE);
			sender = session.createSender(queue);
			Date date = new Date();
			ObjectMessage objectMessage = session.createObjectMessage();
			objectMessage.setObject(date);

			connection.start();

			sender.send(objectMessage);

			System.out.println("The Object is Sent");
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (context != null) {
				try {
					context.close();
				} catch (NamingException e) {
					e.printStackTrace();
				}
			}

			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Sender sender = new Sender();
		sender.sendMessage();

	}

}
